<template>
  <el-card>
    <el-row>
      <el-col :span="12" :offset="4">
        <el-form :model="addshopForm" :rules="addshopFormRules" ref="addshopFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="店铺名称" prop="name">
            <el-input v-model="addshopForm.name"></el-input>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-autocomplete v-model="addshopForm.address" :fetch-suggestions="querySearchAsync" placeholder="请输入地址" style="width: 100%;" @select="addressSelect"></el-autocomplete>
            <span>当前城市：{{ city.name }}</span>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model.number="addshopForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="店铺介绍">
            <el-input v-model="addshopForm.description"></el-input>
          </el-form-item>
          <el-form-item label="店铺标语">
            <el-input v-model="addshopForm.promotion_info"></el-input>
          </el-form-item>
          <el-form-item label="店铺分类">
            <el-cascader v-model="selectedCategory" :options="categoryOptios"></el-cascader>
          </el-form-item>
          <!-- 店铺特点 -->
          <el-form-item label="店铺特点" style="white-space: nowrap;" class="switch_it">
            <span>品牌保证</span>
            <el-switch on-text="" off-text v-model="addshopForm.is_premium"></el-switch>
            <span>蜂鸟专送</span>
            <el-switch on-text="" off-text v-model="addshopForm.delivery_mode"></el-switch>
            <span>新开店铺</span>
            <el-switch on-text="" off-text v-model="addshopForm.new"></el-switch>
          </el-form-item>
          <el-form-item style="white-space: nowrap;" class="switch_it">
            <span>外卖保</span>
            <el-switch on-text="" off-text v-model="addshopForm.bao"></el-switch>
            <span>准时达</span>
            <el-switch on-text="" off-text v-model="addshopForm.zhun"></el-switch>
            <span>开发票</span>
            <el-switch on-text="" off-text v-model="addshopForm.piao"></el-switch>
          </el-form-item>
          <!--  -->
          <el-form-item label="配送费" prop="float_delivery_fee">
            <el-input-number v-model="addshopForm.float_delivery_fee" :min="0" :max="20"></el-input-number>
          </el-form-item>
          <el-form-item label="配送费" prop="float_delivery_fee">
            <el-input-number v-model="addshopForm.float_minimum_order_amount" :min="0" :max="100"></el-input-number>
          </el-form-item>
          <el-form-item label="营业时间" style="white-space: nowrap;" class="select_time">
            <el-time-select
              placeholder="起始时间"
              v-model="addshopForm.startTime"
              :picker-options="{
                start: '08:30',
                step: '00:15',
                end: '18:30'
              }"
            >
            </el-time-select>
            <el-time-select
              placeholder="结束时间"
              v-model="addshopForm.endTime"
              :picker-options="{
                start: '08:30',
                step: '00:15',
                end: '18:30',
                minTime: addshopForm.startTime
              }"
            >
            </el-time-select>
          </el-form-item>

          <!-- 上传图片 -->
          <el-form-item label="上传店铺头像">
            <el-upload class="avatar-uploader" :action="baseURL + '/v1/addimg/shop'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="addshopForm.image_path" :src="baseImgPath + addshopForm.image_path" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传营业执照">
            <el-upload class="avatar-uploader" :action="baseURL + '/v1/addimg/shop'" :show-file-list="false" :on-success="handleAvatarBusiness" :before-upload="beforeAvatarUpload">
              <img v-if="addshopForm.business_license_image" :src="baseImgPath + addshopForm.business_license_image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传餐饮服务许可证">
            <el-upload class="avatar-uploader" :action="baseURL + '/v1/addimg/shop'" :show-file-list="false" :on-success="handleAvatarService" :before-upload="beforeAvatarUpload">
              <img v-if="addshopForm.catering_service_license_image" :src="baseImgPath + addshopForm.catering_service_license_image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <!--  -->
          <el-form-item label="优惠活动">
            <el-select v-model="activityValue" @change="selectActivity" :placeholder="activityValue">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <!-- 添加互动 -->
          <el-table :data="activities" stripe border style="min-width: 600px;margin-bottom: 20px;">
            <el-table-column prop="icon_name" label="活动标题"> </el-table-column>
            <el-table-column prop="name" label="活动名称"> </el-table-column>
            <el-table-column prop="description" label="活动详情"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="hanbleActiveDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 提交 -->
          <el-form-item style="text-align:center;">
            <el-button type="primary" @click="addFormOK">立即创建</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import request from '../api/axiosApi'
import { baseURL, baseImgPath } from '../api/env'
import { addShop, cityGuess, foodCategory } from '../api/index'
export default {
  data() {
    return {
      addshopForm: {
        name: '',
        address: '',
        phone: '',
        description: '',
        promotion_info: '',
        latitude: '',
        longitude: '',
        is_premium: true,
        delivery_mode: true,
        new: true,
        bao: true,
        zhun: true,
        piao: true,
        float_delivery_fee: 5,
        float_minimum_order_amount: 20,
        startTime: '',
        endTime: '',
        image_path: '',
        catering_service_license_image: '',
        business_license_image: ''
      },
      addshopFormRules: {
        name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入联系电话' },
          { type: 'number', message: '电话号码必须是数字' }
        ]
      },
      city: {},
      categoryOptios: [],
      selectedCategory: ['快餐便当', '简餐'],
      baseURL,
      baseImgPath,
      options: [
        {
          value: '满减优惠',
          label: '满减优惠'
        },
        {
          value: '优惠大酬宾',
          label: '优惠大酬宾'
        },
        {
          value: '新用户立减',
          label: '新用户立减'
        },
        {
          value: '进店领券',
          label: '进店领券'
        }
      ],
      activityValue: '满减优惠',
      activities: [
        {
          icon_name: '减',
          name: '满减优惠',
          description: '满30减5，满60减8'
        }
      ]
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      try {
        const { data: city } = await cityGuess()
        const { data: category } = await foodCategory()
        this.city = city
        category.forEach(item => {
          if (item.sub_categories.length) {
            const addnew = {
              value: item.name,
              label: item.name,
              children: []
            }
            item.sub_categories.forEach(subitem => {
              addnew.children.push({
                value: subitem.name,
                label: subitem.name
              })
            })
            this.categoryOptios.push(addnew)
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    async querySearchAsync(queryString, cd) {
      if (queryString) {
        try {
          const { data: cityList } = await request.get(`/v1/pois?type='search'&city_id=${this.city.id}&keyword=${queryString}`)
          if (cityList instanceof Array) {
            cityList.map(item => {
              item.value = item.address
              return item
            })
            cd(cityList)
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    addressSelect(val) {
      this.addshopForm.latitude = val.latitude
      this.addshopForm.longitude = val.longitude
    },
    handleAvatarSuccess(file) {
      if (file.status === 1) {
        this.addshopForm.image_path = file.image_path
      } else {
        this.$message.error('上传图片失败!')
      }
    },

    handleAvatarBusiness(file) {
      if (file.status === 1) {
        this.addshopForm.business_license_image = file.image_path
      } else {
        this.$message.error('上传图片失败!')
      }
    },
    handleAvatarService(file) {
      if (file.status === 1) {
        this.addshopForm.catering_service_license_image = file.image_path
      } else {
        this.$message.error('上传图片失败!')
      }
    },
    beforeAvatarUpload(file) {
      const isRightType = file.type === 'image/jpeg' || file.type === 'image/png'
      const isSize2M = file.size / 1024 / 1024 < 2
      if (!isRightType) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isSize2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
    },
    selectActivity(selectVal) {
      this.$prompt('请输入活动详情', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(resolve => {
          if (resolve.value === null) {
            return this.$message.error('请输入活动详情')
          }
          let newObj = {}
          switch (selectVal) {
            case '满减优惠':
              newObj = {
                icon_name: '减',
                name: '满减优惠',
                description: resolve.value
              }
              break
            case '优惠大酬宾':
              newObj = {
                icon_name: '特',
                name: '优惠大酬宾',
                description: resolve.value
              }
              break
            case '新用户立减':
              newObj = {
                icon_name: '新',
                name: '新用户立减',
                description: resolve.value
              }
              break
            case '进店领券':
              newObj = {
                icon_name: '领',
                name: '进店领券',
                description: resolve.value
              }
              break
          }
          this.activities.push(newObj)
        })
        .catch(() => {
          this.$message.info('已取消输入')
        })
    },
    hanbleActiveDelete(index) {
      this.activities.splice(index, 1)
    },
    // 提交
    addFormOK() {
      this.$refs.addshopFormRef.validate(async valid => {
        if (valid) {
          Object.assign(this.addshopForm, { activities: this.activities }, { category: this.selectedCategory.join('/') })
          try {
            const { data: result } = await addShop(this.addshopForm)
            if (result.status === 1) {
              this.$message.success('添加成功')
              this.addshopForm = {
                name: '',
                address: '',
                phone: '',
                description: '',
                promotion_info: '',
                latitude: '',
                longitude: '',
                is_premium: true,
                delivery_mode: true,
                new: true,
                bao: true,
                zhun: true,
                piao: true,
                float_delivery_fee: 5,
                float_minimum_order_amount: 20,
                startTime: '',
                endTime: '',
                image_path: '',
                catering_service_license_image: '',
                business_license_image: ''
              }
            } else {
              this.$message.error(result.message)
            }
          } catch (error) {
            console.log(error)
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: '请检查输入是否正确',
            offset: 100
          })
          return false
        }
      })
    }
  }
}
</script>

<style lang="less">
.switch_it {
  span {
    margin-right: 10px;
  }
}
.select_time {
  .el-date-editor {
    margin-right: 10px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
